import MQTT from 'mqtt'

const topicList = {};
const options = {
  clean: true,
  connectTimeout: 4000, // 超时时间
  // 认证信息
  clientId: 'iot_info',
  username: 'iot_info',
  password: 'emqx_test',
}

const connectUrl = 'ws://iot.jesseyen.xyz:8083/mqtt';
const emqx = MQTT.connect(connectUrl, options);

emqx.on('connect', () => {
  console.log('mqtt服务器连接成功', connectUrl);
}).on('reconnect', (error) => {
  console.log('正在重连:', error);
}).on('error', (error) => {
  console.log('连接失败:', error);
}).on('message', (topic, payload) => {
  let msgJson = JSON.parse(payload);
  if(!topicList[topic]) return;
  topicList[topic](msgJson);
})

emqx.SubscribeTopic = function(topic, callback) {
  if(typeof(topic) !== 'string' || typeof(callback) !== 'function') return;
  emqx.subscribe(topic);
  topicList[topic] = callback;
}

export {
  emqx
};